package sk.fiit.icp.event.components;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.image.Image;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.request.resource.ContextRelativeResource;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.validation.validator.StringValidator;

import sk.fiit.icp.data.EventCategories;
import sk.fiit.icp.data.EventCategoriesDao;
import sk.fiit.icp.event.view.RegistrationForm;

public class CategoryPanel extends Panel {
	@SpringBean(name = "eventCategoriesDao")
	public EventCategoriesDao eventCategoriesDao;

	public CategoryPanel(String id, final RegistrationForm modalWindowPage, final ModalWindow modalWindow) {
		super( id );
		setOutputMarkupId( true );
	
		add( new CategoryForm( "categoryForm", modalWindow ) );
	}

	class CategoryForm extends Form<EventCategories> {
		final FeedbackPanel feedback = new FeedbackPanel( "feedback" );

		public CategoryForm(String id, final ModalWindow modalWindow) {
			super( id, new CompoundPropertyModel<EventCategories>( new EventCategories() ) );
			setOutputMarkupId( true );
			feedback.setOutputMarkupId( true );
			add( feedback );
			add( new RequiredTextField<String>( "name" ).add( StringValidator.maximumLength( 20 ) ) );
			add( new RequiredTextField<String>( "color" ).add( StringValidator.maximumLength( 7 ) ) );
			add( new TextArea<String>( "description" ).setRequired( true ) );

			AjaxSubmitLink link = new AjaxSubmitLink( "saveLink" ) {

				@Override
				protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
					eventCategoriesDao.persist( getModelObject() );
					modalWindow.close( target );
				}

				@Override
				protected void onError(AjaxRequestTarget target, Form<?> form) {
					target.add( feedback );
					System.out.println( "ZLEEEEEEEEEEEEEE" );
				}
			};

			link.add( new Image( "saveImage", new ContextRelativeResource( "/images/Page/ButtonSave.png" ) ) );
			add( link );
		}
	}

}
